'use strict';
$().ready(function () {
    var action = 'list', user = {}, listData = [], unitListData = [], scoreItem = '', distributionItem = '';
    var state = [{id: 1, name: '已申请'}, {id: 2, name: '已上报'}, {id: 3, name: '已批准'}, {id: 4, name: '维修中'}, {
        id: 5,
        name: '完成'
    }, {id: 6, name: '已取消'}];
    var repair = {
        list: function () {
            var data = {
                pageSize: 9999,
                pageIndex: 1
            };
            switch (user.postCode) {
                case 1 :
                    data.applicantGuid = user.guid;
                    if ($('#searchState').val()) {
                        data.state = $('#searchState').val();
                    }
                    break;
                case 2 :
                    data.enterGuid = user.enterGuid;
                    if ($('#searchState').val()) {
                        data.state = $('#searchState').val();
                    }
                    break;
                case 3 :
                    data.approvalFlag = 1;
                    if ($('#searchUnit').val()) {
                        data.enterGuid = $('#searchUnit').val();
                    }
                    if ($('#searchrepairPeople').val()) {
                        data.executorGuid = $('#searchrepairPeople').val();
                    }
                    if ($('#searchState').val()) {
                        data.state = $('#searchState').val();
                    }
                    break;
                case 4 :
                    if ($('#searchUnit').val()) {
                        data.enterGuid = $('#searchUnit').val();
                    }
                    data.executorGuid = user.guid;
                    if ($('#searchState').val()) {
                        data.state = $('#searchState').val();
                    }
                    break;
                case 5 :
                    if ($('#searchUnit').val()) {
                        data.enterGuid = $('#searchUnit').val();
                    }
                    if ($('#searchrepairPeople').val()) {
                        data.executorGuid = $('#searchrepairPeople').val();
                    }
                    if ($('#searchState').val()) {
                        data.state = $('#searchState').val();
                    }
                    break;
            }
            $.ajax({
                url: "wpdOrder/queryWpdOrderPageList.do",
                data: data,
                dataType: 'json',
                type: 'GET',
                success: function (result) {
                    listData = result.data || [];
                    repair.setData();
                    if (result.extra && result.extra.total) {
                        $('#extraTotal').css('display','block');
                        $('#extraTotal').find('span').html(result.extra.total);
                    } else {
                        $('#extraTotal').css('display','none');
                    }
                },
                error: function (error) {
                    listData = [];
                    console.log(error);
                }
            });
        },
        setData: function () {
            var wap = $('#list-table').find('tbody'), htmlDom = '<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>';
            wap.empty();
            $.each(listData, function (index, item) {
                wap.append(htmlDom);
                wap.find('tr').eq(index).attr('id', 'repair' + item.id);
                var itemDom = wap.find('tr').eq(index).find('td');
                itemDom.eq(0).html(index + 1);
                itemDom.eq(1).html(item.applyTitle);
                itemDom.eq(2).html(item.applyContent);
                itemDom.eq(3).html(item.applicantName);
                itemDom.eq(4).html(repair.formatDateTime(item.applyTime));
                $.each(state, function (key, line) {
                    if (line.id == item.state) {
                        itemDom.eq(5).html(line.name);
                    }
                });
                switch (user.postCode) {
                    case 1 : //普通民警
                        if (item.state == 5 && !item.evaluate) {
                            itemDom.eq(6).append('<a href="javascript:void(0)" class="btn btn-primary">评价</a>');
                        }
                        itemDom.eq(6).find('a').eq(0).bind('click', function () {
                            repair.score(item, 1);
                        });
                        break;
                    case 2 ://所领导
                        if (item.state == 1) {
                            itemDom.eq(6).append('<a href="javascript:void(0)" class="btn btn-primary">上报</a><a href="javascript:void(0)" class="btn btn-primary">撤回</a>');
                        }
                        itemDom.eq(6).find('a').eq(0).bind('click', function () {
                            repair.update(item, 2);
                        });
                        itemDom.eq(6).find('a').eq(1).bind('click', function () {
                            repair.update(item, 6);
                        });
                        break;
                    case 3 : //通讯科
                        if (item.state == 2) {
                            itemDom.eq(6).append('<a href="javascript:void(0)" class="btn btn-primary">分配</a><a href="javascript:void(0)" class="btn btn-primary">拒绝</a>');
                            itemDom.eq(6).find('a').eq(0).bind('click', function () {
                                repair.distribute(item);
                            });
                            itemDom.eq(6).find('a').eq(1).bind('click', function () {
                                repair.update(item, 7);
                            });
                        }
                        if (item.state == 5) {
                            itemDom.eq(6).append('<sapn>评价：'+item.evaluate+'</sapn>');
                        }
                        break;
                    case 4 ://维修人员
                        if (item.state == 3) {
                            itemDom.eq(6).append('<a href="javascript:void(0)" class="btn btn-primary">签收</a>');
                            itemDom.eq(6).find('a').eq(0).bind('click', function () {
                                repair.update(item, 4);
                            });
                        }
                        if (item.state == 4) {
                            itemDom.eq(6).append('<a href="javascript:void(0)" class="btn btn-primary">维修完成</a>');
                            itemDom.eq(6).find('a').eq(0).bind('click', function () {
                                repair.update(item, 5);
                            });
                        }
                        break;
                    case 5 : //管理员
                        if (item.state == 2) {
                            itemDom.eq(6).append('<a href="javascript:void(0)" class="btn btn-primary">分配</a><a href="javascript:void(0)" class="btn btn-primary">拒绝</a>');
                        }
                        itemDom.eq(6).find('a').eq(0).bind('click', function () {
                            repair.distribute(item);
                        });
                        itemDom.eq(6).find('a').eq(1).bind('click', function () {
                            repair.update(item, 7);
                        });
                        break;
                }
            });
        },
        distribute: function (item) {
            distributionItem = item;
            repair.repairPeopleList();
            $('.choiceDateTime').val('');
            $("#distribution").modal('show');
        },
        score: function (item) {
            console.log(item);
            $('#scorevalue').val('');
            scoreItem = item;
            $("#score").modal('show');
        },
        save: function () {
            var data = {
                enterGuid: user.enterGuid,
                state: 1,
                applyTitle: $("#repairTitle").val(),
                applyContent: $("#repairContent").val()
            };
            $.ajax({
                url: "wpdOrder/saveWpdOrder.do",
                data: data,
                dataType: 'json',
                type: 'POST',
                success: function (result) {
                    $('a[href="#list"]').tab('show');
                    repair.tabSwitch(1);
                },
                error: function (error) {
                    console.log(error);
                }
            });
        },
        update: function (item, type) {
            if (type == 1) {
                item = scoreItem;
                if (!$('#scorevalue').val()) {
                    alert('请输入评价');
                    return;
                }
            }
            if (type == 3) {
                item = distributionItem;
                if (!$('#repair-people').val()) {
                    alert('请选择维修人员');
                    return;
                }
                if (!$('#choiceDateTime').val()) {
                    alert('请选择时间');
                    return;
                }
            }
            var data = {
                guid: item.guid
            };
            switch (type) {
                case 1:
                    data.evaluate = $('#scorevalue').val();
                    break;
                case 2:
                    data.approvalFlag = 1;
                    data.state = 2;
                    break;
                case 3:
                    data.sendFlag = 1;
                    data.state = 3;
                    data.executorGuid = $('#repair-people').val();
                    data.exceptRepairTimeStr = new Date($('#choiceDateTime').val()).getTime();
                    break;
                case 4:
                    data.executeFlag = 1;
                    data.state = 4;
                    break;
                case 5:
                    data.executeFlag = 2;
                    data.state = 5;
                    break;
                case 6:
                    data.approvalFlag = 0;
                    data.state = 6;
                    break;
                case 7:
                    data.sendFlag = 0;
                    data.state = 6;
                    break;
            }
            $.ajax({
                url: "wpdOrder/saveWpdOrder.do",
                data: data,
                dataType: 'json',
                type: 'POST',
                success: function (result) {
                    type == 1 && $('#score').modal('hide');
                    type == 3 && $('#distribution').modal('hide');
                    repair.tabSwitch(1);
                },
                error: function (error) {
                    console.log(error);
                }
            });
        },
        cancel: function () {
            $('a[href="#list"]').tab('show');
            repair.tabSwitch(1);
        },
        repairPeopleList: function () {
            var data = {
                pageSize: 9999,
                pageIndex: 1,
                postCode: 4
            };
            $.ajax({
                url: "wpdUser/queryWpdUserPageList.do",
                data: data,
                dataType: 'json',
                type: 'POST',
                success: function (result) {
                    if (result && result.data && result.data.length) {
                        var select = $('#repair-people'), select2 = $('#searchrepairPeople');
                        select.empty().append('<option value="" class="">所有</option>');
                        select2.empty().append('<option value="" class="">所有</option>');
                        $.each(result.data, function (index, item) {
                            select.append("<option value='" + item.guid + "'>" + item.userName + "</option>");
                            select2.append("<option value='" + item.guid + "'>" + item.userName + "</option>");
                        });
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });
        },
        unitList: function () {
            var data = {
                pageSize: 9999,
                pageIndex: 1
            };
            $.ajax({
                url: "wpdEnter/queryWpdEnterPageList.do",
                data: data,
                dataType: 'json',
                type: 'POST',
                success: function (result) {
                    if (result && result.data && result.data.length) {
                        var select = $('#searchUnit'), select2 = $('#depid');
                        select.empty().append('<option value="" class="">全部</option>');
                        select2.empty().append('<option value="" class="">全部</option>');
                        $.each(result.data, function (index, item) {
                            select.append("<option value='" + item.guid + "'>" + item.enterName + "</option>");
                            select2.append("<option value='" + item.guid + "'>" + item.enterName + "</option>");
                        });
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });
        },
        tabSwitch: function (type) {
            if (type == 1) {
                $('#searchUnit').val('');
                $('#repairPeople').val('');
                $('#searchState').val('');
                repair.list();
            }
            if (type == 2) {
                $('#repairTitle').val('');
                $('#repairContent').val('');
            }
        },
        formatDateTime: function (timeStamp) {
            var date = new Date();
            date.setTime(timeStamp);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m < 10 ? ('0' + m) : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            var h = date.getHours();
            h = h < 10 ? ('0' + h) : h;
            var minute = date.getMinutes();
            var second = date.getSeconds();
            minute = minute < 10 ? ('0' + minute) : minute;
            second = second < 10 ? ('0' + second) : second;
            return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
        },
    };
    $('a[href="#list"]').bind('click', function () {
        repair.tabSwitch(1)
    });
    $('a[href="#add"]').bind('click', function () {
        repair.tabSwitch(2)
    });
    $('#submit').bind('click', function () {
        repair.save();
    });
    $('#cancel').bind('click', function () {
        repair.cancel()
    });
    $('#saveScore').bind('click', function () {
        repair.update('score', 1)
    });
    $('#formList').bind('click', function () {
        repair.list();
    });
    $('#saveDistribution').bind('click', function () {
        repair.update('item', 3);
    });
    $('#add-User').bind('click', function () {
        $('#addUser').modal('show');
    });
    $('#add-Unit').bind('click', function () {
        $('#addUnit').modal('show');
    });
    $('#saveUser').bind('click', function () {
        saveUser();
    });
    $('#saveSuo').bind('click', function () {
        saveSuo();
    });
    $('#llevel').bind('change', function () {
        changeUserType();
    });
    function saveUser() {
        var openhref = "wpdUser/saveWpdUser.do";
        var username = document.getElementById("username").value;
        var depid = document.getElementById("depid").value;
        var password = document.getElementById("password").value;
        var password2 = document.getElementById("password2").value;
        var llevel = document.getElementById("llevel").value;
        var cnname = document.getElementById("cnname").value;

        if (username == '') {
            alert("帐号不能为空");
            return false;
        }
        if (cnname == '') {
            alert("姓名不能为空");
            return false;
        }

        if (password == '') {
            alert("密码不能为空");
            return false;
        }
        if (password2 == '') {
            alert("再次确认密码不能为空");
            return false;
        }
        if (password2 != password) {
            alert("两次密码不一致,请重新设置");
            return false;
        }
        var data = {
            "userCode": username,
            "userPassword": password,
            "userName": cnname,
            "postCode": llevel
        };
        if (llevel == 1 || llevel == 2) {
            data.enterGuid = depid;
        }
        $.ajax({
            type: "post",
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            url: openhref,
            data: data,
            success: function (data) {
                if (data.code == 0) {
                    $('#addUser').modal('hide');
                    repari.repairPeopleList();
                } else {
                    alert(data.message);
                }
            }, error: function (XMLHttpRequest, textStatus, errorThrow) {
                console.log(XMLHttpRequest, textStatus, errorThrow);
            }
        });

    };
    function saveSuo() {
        var openhref = "wpdEnter/saveWpdEnter.do";
        var sname = document.getElementById("sname").value;
        if (username == '') {
            alert("名称不能为空");
            return false;
        }
        $.ajax({
            type: "post",
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            url: openhref,
            data: {
                "enterName": sname
            },
            success: function (data) {
                console.log(data);
                if (data.code == 0) {
                    $('#addUnit').modal('hide');
                    repair.unitList();
                } else {
                    alert(data.message);
                }
            }, error: function (XMLHttpRequest, textStatus, errorThrow) {
                console.log(XMLHttpRequest, textStatus, errorThrow);
            }
        });
    };
    function changeUserType() {
        if ($('#llevel').val() == 1 || $('#llevel').val() == 2) {
            $('#user-units').css('display', 'block');
        } else {
            $('#user-units').css('display', 'none');
        }
    };

    var init = (function () {
        if (sessionStorage.user) {
            user = JSON.parse(sessionStorage.user);
        } else {
            alert('请先登陆');
            window.location.href = '../WPD/login.html';
        }
        $(".username").html('您好，'+user.userName);
        $.fn.datetimepicker.dates['zh'] = {
            days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            daysShort: ["日", "一", "二", "三", "四", "五", "六", "日"],
            daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
            months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            monthsShort: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
            meridiem: ["上午", "下午"],
            //suffix:      ["st", "nd", "rd", "th"],
            today: "今天"
        };
        $(".choiceDateTime").datetimepicker({
            format: 'yyyy-mm-dd hh:ii',
            autoclose: true,
            startView: "month",
            minView: 0,
            minuteStep: 1,
            forceParse: 0,
            pickerPosition: 'bottom-left',
            language: 'zh'
        });
        user.postCode = parseInt(user.postCode);
        repair.unitList();
        repair.repairPeopleList();
        $('#add-Unit').css('display','none');
        $('#add-User').css('display','none');
        switch (user.postCode) {
            case 1 :
                $('.unit').css('display', 'none');
                $('.repairPeople').css('display', 'none');
                break;
            case 2 :
                $('.unit').css('display', 'none');
                $('.repairPeople').css('display', 'none');
                break;
            case 4 :
                $('.repairPeople').css('display', 'none');
                break;
            case 5 :
                $('#add-Unit').css('display','block');
                $('#add-User').css('display','block');
                break;
        }
        repair.list();
    })();
});
